/*
 *
 *  Copyright (C) 2012-2024
 *  All rights reserved, Designed By 杭州连线客信息技术有限公司
 *  注意：
 *  本软件为杭州连线客信息技术有限公司开发研制，未经购买不得使用
 *  购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 *  一经发现盗用、分享等行为，将追究法律责任，后果自负
 *
 */

package com.lxk.oms.flow.order;

import cn.hutool.core.collection.CollUtil;
import com.lxk.oms.order.domain.bo.OmsOrderItemBo;
import com.lxk.service.core.Result;
import com.lxk.service.pms.api.PmsServiceApi;
import com.lxk.service.pms.request.CheckSkuStockParam;
import com.lxk.service.pms.response.PmsSkuCheckStockResult;
import com.lxk.service.pms.response.SkuCheckStockItemResult;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.FlowExecutor;
import com.yomahub.liteflow.core.NodeComponent;
import com.yomahub.liteflow.log.LFLog;
import com.yomahub.liteflow.log.LFLoggerManager;
import lombok.AllArgsConstructor;
import org.dromara.common.core.exception.ServiceException;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 检查库存节点
 *
 * @author heyi
 * 2024/8/21
 */
@LiteflowComponent(value = FlowOrderNodeConst.CHECK_STOCK_ORDER)
@AllArgsConstructor
public class OrderCheckStockNode extends NodeComponent {
    private final LFLog log = LFLoggerManager.getLogger(FlowExecutor.class);
    private PmsServiceApi pmsServiceApi;

    @Override
    public void process() throws Exception {
        OrderContext contextBean = getContextBean(OrderContext.class);
        List<OmsOrderItemBo> orderItemBoList = contextBean.getOrderItemBoList();
        List<CheckSkuStockParam> skuStockParams = orderItemBoList.stream().map(item -> {
            Long merId = item.getMerId();
            Long skuId = item.getSkuId();
            Integer count = item.getCount();
            CheckSkuStockParam param = new CheckSkuStockParam();
            param.setMerId(merId);
            param.setSkuId(skuId);
            param.setNum(count);
            return param;
        }).collect(Collectors.toList());
        Result<PmsSkuCheckStockResult> result =
            pmsServiceApi.checkStockBySkuIdList(skuStockParams);
        if (result.isFail()) {
            throw new ServiceException(result.getMsg());
        }
        if (!result.getData().getResult()) {
            List<SkuCheckStockItemResult> skuStockItemList = result.getData().getSkuStockItemList();
            String msg = "库存不足";
            if (CollUtil.isNotEmpty(skuStockItemList)) {
                msg = skuStockItemList.stream().map(SkuCheckStockItemResult::getMessage).collect(Collectors.joining(";"));
            }
            log.error("库存不足:{}", result.getData());
            throw new ServiceException(msg);
        }
    }

    @Override
    public boolean isAccess() {
        OrderContext contextBean = getContextBean(OrderContext.class);
        return contextBean.getNeedStock();
    }
}
